var express = require('express');

var https = require('https');

var fs = require('fs');

var atob = require('atob');

var querystring = require('querystring');

var body = require('body-parser');
const bodyParser = require('body-parser');

var mysql = require('mysql');

var expressip = require('express-ip');

//--------------------------------------------------------------------------------------------------

//MySQL配置
var connection = mysql.createPool({
    host: "数据库IP地址",
    port: "端口",
    user: "用户名",
    password: "密码",
    database: "dsrblog" //别动
})

//版本号，请勿修改
var vision = 'DSRBLOG v2.3.11';

//--------------------------------------------------------------------------------------------------

//创建http服务器
var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(expressip().getIpInfoMiddleware);

//获取用户设备类型与访问IP
app.post('/userInfo', (req, res) => {
    console.log(req.ip);
    res.send();
})

//请求根目录（引导页）
app.get('/', (req, res) => {
    fs.readFile('./index.html', 'utf8', function (err, data) {
        if (err) data = '404';

        connection.getConnection(function (err, connection) {
            if (err) throw err;
            connection.query("SELECT * FROM myinfo", function (err, results, fields) {
                if (err) throw error;

                res.setHeader('Content-Type', 'text/html;charset=utf-8');
                res.write(data.replace('this is my slogan', results[0].slogan).replace('blogversion', vision));
                res.end();
            });
            connection.release();
        })
    })
})

//请求/view目录（其他页面）
app.get('/view', (req, res) => {
    fs.readFile('./view/blog.html', 'utf8', function (err, data) {
        if (err) data = '404';

        connection.getConnection(function (err, connection) {
            if (err) throw error;
            connection.query("SELECT * FROM myinfo", function (err, results, fields) {
                if (err) throw error;

                res.setHeader('Content-Type', 'text/html;charset=utf-8');
                res.write(data.replace('this is my slogan', results[0].slogan).replace('blogversion', vision));
                res.end();
            });
            connection.release();
        })
    })
})

//请求iframe（内嵌功能页面）
app.use('/iframe', (req, res) => {
    fs.readFile('./iframe' + req.url, 'utf8', function (err, data) {
        if (err) data = '<h1>404</h1>';

        res.setHeader('Content-Type', 'text/html;charset=utf-8');
        res.write(data);
        res.end();
    })
})

//请求静态资源
app.use('/public', (req, res) => {
    fs.readFile('./public' + req.url, function (err, data) {
        if (err) res.send('404');
        res.write(data);
        res.end();
    })
})

//--------------------------------------------------------------------------------------------------

//请求Dynamic数据库
app.post('/dynamic', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;
        connection.query("", function (err, results, fields) {
            err == null ? [
                res.send('200')
            ] : [
                res.send('404')
            ]
        });
        connection.release();
    })
})

//--------------------------------------------------------------------------------------------------

//-----友链模块-----

var friendmsgs = [];
var friendmax = 0;//初始化friend表数据总量

var priorityMax = 3;//最大优先级(0~3)

//请求友链信息并传递给对应的AJAX
app.post('/friend', (req, res) => {

    //初始化
    friendmsgs = [];
    friendmax = 0;

    connection.getConnection(function (err, connection) {
        if (err) throw error;
        //获取friend表数据总量
        connection.query("SELECT COUNT(*) AS friendMax FROM friend", function (err, results, fields) {
            if (err) throw error;
            friendmax = results[0].friendMax;
        });

        //获取myinfo表的所有内容
        connection.query("SELECT * FROM myinfo", function (err, results, fields) {
            if (err) throw error;
            friendmsgs = [];

            var myinfo = { id: results[0].ID, slogan: results[0].slogan, imgsrc: results[0].imgsrc, blogurl: '/view', display: 1, priority: 3, state: 0 }

            friendmsgs.push(myinfo);
        });

        //获取friend表的所有内容
        connection.query("SELECT * FROM friend", function (err, results, fields) {
            if (err) throw error;

            //判断显示优先级
            for (var p = priorityMax; p >= 0; p--) {
                //判断是否显示
                for (var i = 0; i < friendmax; i++) {
                    var msg = { id: results[i].ID, slogan: results[i].slogan, imgsrc: results[i].imgsrc, blogurl: results[i].blogurl, display: results[i].display, priority: results[i].priority, state: results[i].state };
                    if (msg.display == '1' && msg.priority == p) {
                        friendmsgs.push(msg);
                    }
                }
            }
            res.json(friendmsgs);
        });
        connection.release();
    });
})

//查询指定字段所在行
//SELECT * FROM friend WHERE FIND_IN_SET('2366715664@qq.com',email)

//发送友链申请到MySQL
app.post('/FriendAdd', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;
        connection.query("INSERT INTO friend VALUES('" + req.body.id + "','" + req.body.email + "','" + req.body.password + "','" + req.body.slogan + "','" + req.body.imgsrc + "','" + req.body.blogurl + "', DEFAULT, DEFAULT, DEFAULT)", function (err, results, fields) {
            err == null ? [
                res.send('200')
            ] : [
                res.send('404')
            ]
        });
        connection.release();
    })
})

//修改信息验证身份
app.post('/ModifyConfirm', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;
        connection.query("SELECT * FROM friend WHERE email='" + req.body.email + "'", function (err, results, fields) {
            err == null && results != '' ? [
                results[0].password == req.body.password ? [
                    res.json(results[0])
                ] : [
                    res.send('404')
                ]
            ] : [
                res.send('404')
            ]
        });
        connection.release();
    })
})

//修改友链申请到MySQL
app.post('/FriendModify', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;
        connection.query("UPDATE friend SET ID='" + req.body.id + "',slogan ='" + req.body.slogan + "', imgsrc ='" + req.body.imgsrc + "',blogurl ='" + req.body.blogurl + "' WHERE email = '" + req.body.email + "'", function (err, results, fields) {
            err == null ? [
                res.send('200')
            ] : [
                res.send('404')
            ]
        });
        connection.release();
    })
})

//--------------------------------------------------------------------------------------------------

//-----管理后台-----

//请求login登录面板
app.get('/login', (req, res) => {
    fs.readFile('./login/login.html', 'utf8', function (err, data) {
        if (err) data = '404';

        res.setHeader('Content-Type', 'text/html;charset=utf-8');
        res.write(data);
        res.end();
    })
})
//验证login登录信息
app.post('/loginstate', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;

        connection.query("SELECT * FROM myinfo", function (err, results, fields) {
            if (err) res.send('404');
            (req.body.email == results[0].email && req.body.password == results[0].password) ? [
                res.send('200')
            ] : [
                res.send('404')
            ]
        });
        connection.release();
    })
})
//请求admin登录面板
app.get('/admin', (req, res) => {

    fs.readFile('./admin/admin.html', 'utf8', function (err, data) {
        if (err) data = '404';

        res.setHeader('Content-Type', 'text/html;charset=utf-8');
        res.write(data);
        res.end();
    })
})

//获取myinfo
app.post('/myinfo', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw err;
        connection.query("SELECT * FROM myinfo", function (err, results, fields) {
            if (err) throw error;
            res.json(results[0]);
        });
        connection.release();
    })
})

//提交myinfo信息修改
app.post('/saveinfo', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;
        connection.query("UPDATE myinfo SET ID='" + req.body.id + "',slogan ='" + req.body.slogan + "',imgsrc ='" + req.body.imgsrc + "' WHERE email = 'dsr213.inc@gmail.com'", function (err, results, fields) {
            err == null ? [
                res.send('200')
            ] : [
                res.send('404')
            ]
        });
        connection.release();
    })
})

var auditmsgs = [];
var auditmax = 0;//初始化friend表数据总量

var auditpriorityMax = 3;//最大优先级(0~3)

//请求友链审核信息
app.post('/friendAudit', (req, res) => {

    //初始化
    auditmsgs = [];
    auditmax = 0;

    connection.getConnection(function (err, connection) {
        if (err) throw error;
        //获取friend表数据总量
        connection.query("SELECT COUNT(*) AS friendMax FROM friend", function (err, results, fields) {
            if (err) throw error;
            auditmax = results[0].friendMax;
        });

        //获取friend表的所有内容
        connection.query("SELECT * FROM friend", function (err, results, fields) {
            if (err) throw error;

            //根据显示优先级排序
            for (var p = auditpriorityMax; p >= 0; p--) {
                for (var i = 0; i < auditmax; i++) {
                    var msg = { id: results[i].ID, slogan: results[i].slogan, imgsrc: results[i].imgsrc, blogurl: results[i].blogurl, display: results[i].display, priority: results[i].priority, state: results[i].state };
                    if (msg.priority == p) {
                        auditmsgs.push(msg);
                    }
                }
            }
            res.json(auditmsgs);
        });
        connection.release();
    });
})

//删除或驳回友链申请
app.post('/rejected', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;
        connection.query("DELETE FROM friend WHERE blogurl='" + req.body.blogurl + "'", function (err, results, fields) {
            err == null ? [
                res.send('200')
            ] : [
                res.send('404')
            ]
        });
        connection.release();
    })
    console.log("已删除博客网址为：'" + req.body.blogurl + "' 的友链");
})

//通过友链申请
app.post('/agree', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;
        connection.query("UPDATE friend SET display = '1', priority ='" + req.body.priority + "' WHERE blogurl='" + req.body.blogurl + "'", function (err, results, fields) {
            err == null ? [
                res.send('200')
            ] : [
                res.send('404')
            ]
        });
        connection.release();
    })
    console.log("已完成对友链：'" + req.body.blogurl + "' 的修改");
})


//发布动态
app.post('/uploadDynamic', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;
        connection.query("INSERT INTO dynamic VALUES('" + req.body.imgsrc + "','" + req.body.text + "',DEFAULT,'" + req.body.mime + "','" + req.body.length + "')", function (err, results, fields) {
            err == null ? [
                res.send('200')
            ] : [
                res.send('404')
            ]
        });
        connection.release();
    })
})


//接收动态
app.post('/getDynamic', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;
        //获取dynamic表的所有内容
        connection.query("SELECT * FROM dynamic", function (err, results, fields) {
            if (err) throw error;

            res.json(results);
        });
        connection.release();
    });
})

//获取音乐列表
app.post('/musiclist', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;
        //获取dynamic表的所有内容
        connection.query("SELECT * FROM music", function (err, results, fields) {
            if (err) throw error;
            res.json(results);
        });
        connection.release();
    });
})

//处理客户端音乐报错
app.post('/musicerror', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;
        connection.query("UPDATE music SET state = '" + req.body.state + "' WHERE songid='" + req.body.songid + "'", function (err, results, fields) {
            err == null ? [
                res.send('200')
            ] : [
                res.send('404')
            ]
        });
        connection.release();
    })
})

//增加音乐
app.post('/musicadd', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;

        //判断音乐是否有重复
        connection.query("SELECT * FROM music WHERE songid='" + req.body.songid + "'", function (err, results, fields) {
            (results.length != 0) ? [
                res.send('repeat')
            ] : [
                connection.query("INSERT INTO music VALUES('" + req.body.songid + "','" + req.body.songname + "',DEFAULT,'" + req.body.duration + "')", function (err, results, fields) {
                    err == null ? [
                        res.send('200')
                    ] : [
                        res.send('404')
                    ]
                })
            ]
        });
        connection.release();
    });
})

//删除音乐
app.post('/musicdel', (req, res) => {
    connection.getConnection(function (err, connection) {
        if (err) throw error;

        connection.query("DELETE FROM music WHERE songid='" + req.body.songid + "'", function (err, results, fields) {
            err == null ? [
                res.send('200')
            ] : [
                res.send('404')
            ]
        });
        connection.release();
    });
})

//解析分享链接
function getRedirectTarget(url) {
    return new Promise((resolve, reject) => {
        try {
            https.get(url, (res) => {
                let target = '';
                if (res.statusCode - 300 < 100) {
                    target = res.headers.location || '';
                }
                res.resume();
                resolve(target);
            })
        } catch (e) {
            reject(e);
        }
    });
}

app.post('/parsing', (req, res) => {
    async function main() {
        const url = req.body.url;
        const target = await getRedirectTarget(url);
        if (target == '')
        {
            res.send('404');
        }
        else
        {
            var songid = target.substring(target.indexOf('songid=') + 7, target.indexOf('&', target.indexOf('songid=')));
            if(!songid){
                songid = target.substring(target.indexOf('songmid=') + 8, target.indexOf('&', target.indexOf('songmid=')));
            }
            
            res.json(songid);
        }
            
    }

    main().catch((e) => {
        console.error(e);
        process.exit(1);
    });
})

//--------------------------------------------------------------------------------------------------

//启动服务器
app.listen(8080, function () {
    console.log('HTTP服务器启动成功')
})

